<script setup>
import TopNav from "@/components/TopNav.vue";
import Hero from "@/components/Hero.vue";
import MediaNav from "@/components/MediaNav.vue";
import MovieInfo from "@/components/MovieInfo.vue";
import Credits from "@/components/Credits.vue";
import ListingCarousel from "@/components/ListingCarousel.vue";
import Images from "@/components/Images.vue";
import { computed, ref } from "vue";
import { getMovie, getMovieRecommended } from "@/api";
import { useRoute } from "vue-router";
import { useDetails } from "@/hooks/useDetails";

const item = ref(null);
const details = ref();
const recommended = ref(null);
const activeMenu = ref("overview");

const route = useRoute();

getMovie(route.params.id).then((res) => {
  if (item.adult) {
    console.log("This movie is not available");
  } else {
    item.value = res;
    details.value = useDetails(item.value);
  }
});

getMovieRecommended(route.params.id).then((res) => {
  recommended.value = res.results;
});

const metaTitle = computed(() => {
  if (details.value?.yearStart) {
    return `${details.value?.name} (${details.value?.yearStart})`;
  } else {
    return `${details.value?.name}`;
  }
});

const showCredits = computed(() => {
  const credits = item.value?.credits;
  return credits && credits.cast && credits.cast.length;
});

const showEpisodes = computed(() => {
  return item.value?.number_of_seasons;
});

const showVideos = computed(() => {
  const videos = item.value?.videos;
  return videos && videos.results && videos.results.length;
});

const showImages = computed(() => {
  const images = item.value?.images;
  return (
    images &&
    ((images.backdrops && images.backdrops.length) ||
      (images.posters && images.posters.length))
  );
});

const menu = computed(() => {
  const menu = ["Overview"];
  if (showEpisodes.value) {
    menu.push("Episodes");
  }
  if (showImages.value) {
    menu.push("Photos");
  }
  return menu;
});

const navClicked = (menu) => {
  activeMenu.value = menu;
};
</script>

<template>
  <main>
    <TopNav :title="metaTitle" />
    <Hero :item="item" v-if="item" />
    <MediaNav :menu="menu" @clicked="navClicked" />
    <template v-if="activeMenu === 'overview'">
      <MovieInfo :item="item" v-if="item" />
      <Credits v-if="showCredits" :people="item.credits.cast" />
    </template>
    <template v-if="activeMenu === 'photos' && showImages">
      <Images
        v-if="item.images.backdrops.length"
        title="Backdrops"
        type="backdrop"
        :images="item.images.backdrops" />

      <Images
        v-if="item.images.posters.length"
        title="Posters"
        type="poster"
        :images="item.images.posters" />
    </template>

    <ListingCarousel
      v-if="recommended && recommended.length"
      title="More Like This"
      :items="recommended"
    />

  </main>
</template>
